package cn.bankAutoOffice.controller;

import cn.bankAutoOffice.bean.entity.File;
import cn.bankAutoOffice.common.utils.Result;
import cn.bankAutoOffice.service.FileService;
import cn.bankAutoOffice.service.RedisService;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import static cn.bankAutoOffice.common.utils.ResultCodeEnum.SYS_FILE_NOT_EMPTY_ERROR;

/**
 * @author 金健伟
 * @DATE 2023/4/12 11:21
 * 功能说明：
 */

@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileService fileService;

    @Resource
    private RedisService redisService;

    @GetMapping("/fileAll")
    public Result getDocumentAll(@RequestParam("currentPage") Integer currentPage,
                                 @RequestParam("pageSize") Integer pageSize,
                                 @RequestParam(value = "fileType",required = false) Integer fileType){
        PageInfo pageInfo;
        List<File> discussTitle;
        Integer countFile = fileService.countFile(fileType);
        String fileCount = redisService.getValue("allFile" + fileType + currentPage);
        if (fileCount != null){
            discussTitle = JSONObject.parseArray(fileCount,File.class);
            pageInfo = new PageInfo(discussTitle);
            pageInfo.setTotal(countFile);
        } else {
            PageHelper.startPage(currentPage,pageSize);
            discussTitle = fileService.getFileAll(fileType);
            pageInfo = new PageInfo<>(discussTitle);
            redisService.putValue("allFile" + currentPage, discussTitle, 60);
            redisService.putValue("allFileCount",pageInfo.getTotal(),60);
        }

        return Result.success(pageInfo);
    }

    @GetMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.failure(SYS_FILE_NOT_EMPTY_ERROR);
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        String type = FileUtil.extName(fileName);
        // long size = file.getSize();
        String uuid = IdUtil.fastSimpleUUID();
        // String fileUUID = uuid + StrUtil.DOT + type;
        java.io.File uploadFile = new java.io.File("D:\\vueDemo\\"+fileName);

        if(!uploadFile.getParentFile().exists()){
            uploadFile.getParentFile().mkdirs();
        }
        try {
            // 保存文件
            file.transferTo(uploadFile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        File file1 = new File();
        file1.setFileName(fileName);
        String path = uploadFile.getAbsolutePath();
        file1.setUrl(path.substring(0,path.lastIndexOf(fileName)));

        Integer integer = fileService.addFile(file1);
        if (integer > 0){
            return Result.success(uploadFile);
        } else {
            return Result.failure();
        }
    }

    @GetMapping("/down")
    public void down(HttpServletResponse response ,
                     @RequestParam("fileName") String fileName) throws IOException {
        File file1 = fileService.getFile(fileName);
        if (file1 != null) {
            String realPath = "D:\\vueDemo";
            java.io.File file = new java.io.File(realPath, fileName);
            ServletOutputStream os = response.getOutputStream();
            if (file.exists()) {
                // 设置强制下载不打开
                response.setContentType("application/force-download");
                response.setHeader("Content-type", "application-download");
                // response.setContentType("application/octet-stream");
                //设置文件名
                response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

            }
            os.write(FileUtil.readBytes(file));
            os.flush();
            os.close();
        }
    }

}
